import { useEffect, useRef, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { useGameStore } from '../store/gameStore';
import { SkillType } from '../systems/SkillSystem';
import { getLevelConfig } from '../data/levels';
import GameBoard from '../components/GameBoard';
import UnitPanel from '../components/UnitPanel';
import GameUI from '../components/GameUI';
import PauseMenu from '../components/PauseMenu';
import GameResult from '../components/GameResult';
import SkillPanel from '../components/SkillPanel';
import MoodPanel from '../components/MoodPanel';
import InkBackground from '../components/InkBackground';

export default function GameBattle() {
  const { mode, level } = useParams<{ mode: string; level: string }>();
  const navigate = useNavigate();
  const gameLoopRef = useRef<number>();
  const [selectedSkill, setSelectedSkill] = useState<SkillType | null>(null);
  
  const {
    gameState,
    currentLevel,
    initializeGame,
    updateGameState,
    updateGameLogic,
    startNextWave,
    pauseGame,
    resumeGame,
    endGame
  } = useGameStore();

  // 初始化游戏
  useEffect(() => {
    if (!mode || !level) {
      navigate('/');
      return;
    }

    const levelId = `${mode}_${level}`;
    const levelConfig = getLevelConfig(levelId);
    
    if (!levelConfig) {
      console.error(`Level config not found: ${levelId}`);
      navigate('/levels');
      return;
    }

    initializeGame(levelConfig);
    
    // 延迟开始第一波敌军
    setTimeout(() => {
      startNextWave();
    }, 2000);
  }, [mode, level, initializeGame, navigate]);

  // 游戏主循环
  useEffect(() => {
    if (gameState.gameStatus !== 'playing') {
      if (gameLoopRef.current) {
        cancelAnimationFrame(gameLoopRef.current);
      }
      return;
    }

    const gameLoop = (currentTime: number) => {
      const deltaTime = currentTime - gameState.lastUpdateTime;
      
      // 更新游戏逻辑
      handleGameLogicUpdate(deltaTime);
      
      // 继续游戏循环
      gameLoopRef.current = requestAnimationFrame(gameLoop);
    };

    gameLoopRef.current = requestAnimationFrame(gameLoop);

    return () => {
      if (gameLoopRef.current) {
        cancelAnimationFrame(gameLoopRef.current);
      }
    };
  }, [gameState.gameStatus, gameState.lastUpdateTime]);

  // 更新游戏逻辑
  const handleGameLogicUpdate = (deltaTime: number) => {
    // 使用store中的游戏逻辑更新方法
    updateGameLogic(deltaTime);
  };

  // 处理键盘事件
  useEffect(() => {
    const handleKeyPress = (event: KeyboardEvent) => {
      switch (event.key) {
        case 'Escape':
        case ' ': // 空格键
          if (gameState.gameStatus === 'playing') {
            pauseGame();
          } else if (gameState.gameStatus === 'paused') {
            resumeGame();
          }
          break;
        case '1':
        case '2':
        case '3':
        case '4':
        case '5':
        case '6':
        case '7':
          // 快捷键选择单位
          const unitTypes = ['soldier', 'cannon', 'horse', 'chariot', 'advisor', 'minister', 'general'];
          const unitIndex = parseInt(event.key) - 1;
          if (unitIndex < unitTypes.length && currentLevel?.allowedUnits.includes(unitTypes[unitIndex] as any)) {
            useGameStore.getState().selectUnit(unitTypes[unitIndex] as any);
          }
          break;
      }
    };

    window.addEventListener('keydown', handleKeyPress);
    return () => window.removeEventListener('keydown', handleKeyPress);
  }, [gameState.gameStatus, currentLevel, pauseGame, resumeGame]);

  if (!currentLevel) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-white text-xl">加载中...</div>
      </div>
    );
  }

  return (
    <div className="relative w-full h-screen overflow-hidden bg-gradient-to-b from-amber-50 to-amber-100">
      {/* 水墨背景 */}
      <InkBackground intensity="light" animated={true} />
      {/* 游戏背景 */}
      <div className="absolute inset-0 opacity-20">
        <div className="w-full h-full bg-[url('')] bg-repeat"></div>
      </div>

      {/* 游戏UI顶部 */}
      <GameUI />

      {/* 主游戏区域 */}
      <div className="flex h-full pt-16">
        {/* 左侧单位面板 */}
        <div className="w-64 bg-black/20 backdrop-blur-sm border-r border-amber-600/30">
          <UnitPanel />
        </div>

        {/* 中央游戏棋盘 */}
        <div className="flex-1 flex items-center justify-center p-4">
          <GameBoard />
        </div>

        {/* 右侧信息面板 */}
        <div className="w-64 bg-black/20 backdrop-blur-sm border-l border-amber-600/30 p-4">
          <div className="text-amber-900 space-y-4">
            <div className="bg-amber-100/50 rounded-lg p-3 border border-amber-600/30">
              <h3 className="font-bold text-lg mb-2">关卡信息</h3>
              <p className="text-sm">名称: {currentLevel.name}</p>
              <p className="text-sm">模式: {currentLevel.mode === 'campaign' ? '战役' : currentLevel.mode === 'endless' ? '无尽' : '解谜'}</p>
              <p className="text-sm">波次: {gameState.currentWave + 1}/{gameState.totalWaves}</p>
            </div>

            {/* 技能面板 */}
            <div className="mb-4">
              <SkillPanel 
                selectedSkill={selectedSkill}
                onSkillSelect={setSelectedSkill}
              />
            </div>

            {/* 意境收集面板 */}
            <div className="mb-4">
              <MoodPanel />
            </div>

            <div className="bg-amber-100/50 rounded-lg p-3 border border-amber-600/30">
              <h3 className="font-bold text-lg mb-2">游戏状态</h3>
              <p className="text-sm">生命值: {gameState.playerHealth}</p>
              <p className="text-sm">棋魂: {gameState.chessSpirit}</p>
              <p className="text-sm">意境: {gameState.moodValue}</p>
              <p className="text-sm">单位数: {gameState.units.length}</p>
              <p className="text-sm">敌军数: {gameState.enemies.length}</p>
            </div>

            <div className="bg-amber-100/50 rounded-lg p-3 border border-amber-600/30">
              <h3 className="font-bold text-lg mb-2">操作提示</h3>
              <div className="text-xs space-y-1">
                <p>ESC/空格: 暂停游戏</p>
                <p>1-7: 快捷选择单位</p>
                <p>点击棋盘: 部署单位</p>
                <p>右键单位: 升级/出售</p>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* 暂停菜单 */}
      {gameState.gameStatus === 'paused' && <PauseMenu />}

      {/* 游戏结算界面 */}
      {(gameState.gameStatus === 'victory' || gameState.gameStatus === 'defeat') && (
        <GameResult 
          isVisible={gameState.gameStatus === 'victory' || gameState.gameStatus === 'defeat'}
          onClose={() => {/* 结算界面关闭逻辑 */}}
          levelId={`${mode}_${level}`}
          gameResult={{
            completed: gameState.gameStatus === 'victory',
            score: gameState.score,
            time: gameState.gameTime,
            healthRemaining: gameState.playerHealth,
            maxHealth: 100, // 假设最大生命值为100
            unitsUsed: gameState.units.length,
            skillsUsed: Object.values(gameState.skills || {}).reduce((sum, skill) => 
              sum + (skill.lastUsedTime ? 1 : 0), 0
            ),
            moodCollected: gameState.moodValue,
            waveReached: gameState.currentWave,
            maxWave: 5 // 假设最大波次为5
          }}
        />
      )}
    </div>
  );
}